﻿using UnityEngine;
using System.Collections;
using Dict.DataModel;
using ProtoBuf.Message;
using System.Collections.Generic;
#if !NAKED
using supersdkUnity;
#endif
//using Newtonsoft.Json;
using UI;
using Login;
/// <summary>
/// SDK回调
/// </summary>
public class PlatformSDKCallBack : MonoBehaviour
{
#if !NAKED
    private string uid = "";

    public string Uid
    {
        get
        {
            return uid;
        }
        set
        {
            uid = value;
        }
    }
    private string app_data = "";
    public string APP_DATA
    {
        get
        {
            //Debug.Log("[DEBUG] uid = " + app_data);
            return app_data;
        }
        set
        {
            app_data = value;
            //Debug.Log("[DEBUG] UID value:" + app_data);
        }
    }

    private SuperSDKResultInfo resultInfo;
    private SuperSDKUserInfo userInfo;
    private supersdkUnity.SuperSDKPayInfo payInfo;
    private SuperSDKErrorInfo errorInfo;
    public static PlatformSDKCallBack _instance;

    public LoginManager manager
    {
        get
        {
            GameObject loginObj = GameObject.Find("/UI Root/loginUI");
            if (loginObj != null)
            {
                return loginObj.GetComponent<LoginManager>();
            }
            return null;
        }
    }


    void Start()
    {
        #region Bugly
#if !NAKED
        BuglyAgent.ConfigDebugMode(true);
#if UNITY_ANDROID
        BuglyAgent.InitWithAppId("900041488");
        Debug.Log("BUGLY init end");
#endif
#if UNITY_IPHONE || UNITY_IOS
                    BuglyAgent.InitWithAppId("2945440af8");
#endif



        //如果在Android，或者IOS工程中初始化了，就只需要调用这个方法（防止异常闪退）
        //  BuglyAgent.EnableExceptionHandler();

        //注册LogCallbackDelegate回调方法， 处理系统的日志。（防止无法捕获异常）
        //    BuglyAgent.RegisterLogCallback(CallbackDelegate.Instance.OnApplicationLogCallbackHandler);


#endif

        #endregion
        DontDestroyOnLoad(gameObject);
        _instance = this;
        Debug.Log("PlatformSDKCallBack Start");

        if (GameConfig.Instance.platform == 2)
        {
#if !NAKED
            PlatformSDK.GetInstance().Init();
#endif
        }
  
    }
    /// <summary>
    /// 极光回调
    /// </summary>
    /// <param name="jpush"></param>
    public void JpushCallBack(string jpush)
    {

    }

    void TestException()
    {
        string[] str = { "1", "2" };
        foreach (var item in str)
        {
            Debug.Log("str:" + item);
        }
        Debug.Log("Exception:" + str[111]);
    }
   
    /// <summary>
    /// 用户系统回掉
    /// </summary>
    /// <param name="data"></param>
    public void UserCallBackFun(string data)
    {
        //resultInfo = new SuperSDKResultInfo(data);
        Debug.Log("PlatformSDKCallBack UserCallBackFun==>" + data);
        resultInfo = SuperSDKJson.JsonToResultInfo(data);
        if (resultInfo.hasResData()) //判断是否有消息体
        {
            Debug.Log("resultInfo.hasResData");
            userInfo = new SuperSDKUserInfo(resultInfo.resData);
        }
        TestException();
        //回掉内容
        switch (resultInfo.getUserAction())
        {
            case SuperSDKUserAction.INIT_SUCCESS://初始化成功
                Debug.Log("PlatformSDKCallBack UserCallBackFun InitSuccess");
                
#if UNITY_ANDROID
                SuperSDKJPUSH.init(true);
#endif
                break;
            case SuperSDKUserAction.INIT_FAIL://初始化失败
                Debug.Log("PlatformSDKCallBack UserCallBackFun INIT_FAIL");

                //PlatformSDK.GetInstance().Init();
                BoxManager.CreatePopupTextBox(LanguageTool.GetTextNoUpdate(1061));
                break;

            case SuperSDKUserAction.LOGIN_SUCCESS://登陆成功
                Debug.Log("PlatformSDKCallBack UserCallBackFun LOGIN_SUCCESS");
#if UNITY_ANDROID
                SuperSDKJPUSH.setListener("PlatformSDKCallBack", "jpushCallback");
                //极光的
                SuperSDKJPUSH.setAlias(uid);
#endif
                /**
                * 通过getExtra（）获取自定义字段
                * */
                StaticData.UserName = userInfo.getUid();
#region Bugly
                BuglyAgent.SetUserId(userInfo.getUid());
#endregion

                if (userInfo.getExtra().ContainsKey(SuperSDKDataKeys.User.APP_DATA))
                {
                    StaticData.PassWord = userInfo.getExtra()[SuperSDKDataKeys.User.APP_DATA];
                }

                if (manager != null)
                {
                    manager.LoginAuthPass();
                    Debug.Log("SDKCallBack manager!= null");
                }
                if (GameConfig.Instance.GetChannelId == ChannelId.YouKu)
                {
                    GameConfig.Instance.userLogin = true;
                }
                break;
            case SuperSDKUserAction.LOGIN_CANCEL://登录取消
                Debug.Log("PlatformSDKCallBack UserCallBackFun LOGIN_CANCEL ");

                break;
            case SuperSDKUserAction.LOGIN_FAIL://登录失败
                Debug.Log("PlatformSDKCallBack UserCallBackFun LoginFail");
                StaticData.isLogining = false;
                errorInfo = new SuperSDKErrorInfo(userInfo);
               
                int error_no = errorInfo.errorNo;
                string error_msg = errorInfo.errorMsg;
                Debug.Log("PlatformSDKCallBack UserCallBackFun LOGIN_FAIL error_no = " + error_no + " error_msg = " + error_msg);
                //if (GameConfig.Instance.GetChannelId != ChannelId.YingYongBao)//应用宝的错误消息，SuperSDK会提示，这里提示的是非应用宝的渠道
                //{
                    BoxManager.CreatePopupTextBox(LanguageTool.GetTextNoUpdate(1057)); 
                //}
               
                switch (errorInfo.action)
                {
                    case SuperSDKErrorAction.SDK_TOKEN_INVALID://当前用户会话过期，重新登录
                        PlatformSDK.GetInstance().Logout();

                        break;
                    default:
                        break;
                }
                break;
            case SuperSDKUserAction.LOGOUT_SUCCESS://登出成功(注销)
                Debug.Log("PlatformSDKCallBack UserCallBackFun LOGOUT_SUCCESS ");
                StaticData.isLogining = false;
                StaticData.playerData.ClearSelectServerCache();

                StaticData.UserName = "";
                StaticData.PassWord = "";
                ManagerController.Instance.BackToLogin();
                break;
            case SuperSDKUserAction.PLATFORM_ENTER://平台中心进入回调
                Debug.Log("PlatformSDKCallBack UserCallBackFun PLATFORM_ENTER ");

                break;
            case SuperSDKUserAction.PAUSE_PAGE://暂停界面回调
                Debug.Log("PlatformSDKCallBack UserCallBackFun PAUSE_PAGE ");

                break;
            case SuperSDKUserAction.EXIT_PAGE://退出回调
                  Debug.Log("PlatformSDKCallBack UserCallBackFun EXIT_PAGE ");
                if (resultInfo.hasResData())
                {
                    if (!string.IsNullOrEmpty(userInfo.getUid()))
                    {
                        PlatformSDK.GetInstance().ExitGameSubmit();
                    }
                    StaticData.isLogining = false;
                }
                Application.Quit();


                break;
            case SuperSDKUserAction.ANTIADDICTION_QUERY://防沉迷查询回调
                Debug.Log("PlatformSDKCallBack UserCallBackFun：ANTIADDICTION_QUERY" + userInfo.getRealNameRegister());

                break;
            case SuperSDKUserAction.REALNAME_REGISTER://实名注册回调
                Debug.Log("PlatformSDKCallBack UserCallBackFun：REALNAME_REGISTER");

                break;
            case SuperSDKUserAction.ACCOUNTSWITCH_SUCCESS://切换账号成功
                Debug.Log("PlatformSDKCallBack UserCallBackFun：ACCOUNTSWITCH_SUCCESS");
                // PlatformSDK.GetInstance().isSwitch = true;
                StaticData.isLogining = false;
                //直接做重登处理
                StaticData.playerData.ClearSelectServerCache();
                if (GameConfig.Instance.GetChannelId == ChannelId.KaoPu)
                {
                    StaticData.UserName = userInfo.getUid();
                    if (userInfo.getExtra().ContainsKey(SuperSDKDataKeys.User.APP_DATA))
                    {
                        StaticData.PassWord = userInfo.getExtra()[SuperSDKDataKeys.User.APP_DATA];
                    }
                    GameConfig.Instance.isSwitch = true;
                }
                else
                {
                    StaticData.UserName = "";
                    StaticData.PassWord = "";
                }
               
                ManagerController.Instance.BackToLogin();
                break;
            case SuperSDKUserAction.ACCOUNTSWITCH_FAIL://切换账号失败
               StaticData.isLogining = false;
                Debug.Log("PlatformSDKCallBack UserCallBackFun：ACCOUNTSWITCH_FAIL");
                /**
                 * 有些渠道切换账号是，会退出前一个账号，如果切换失败，则没有用户在线，此时需要重新调用登录接口
                 * */
                if (GameConfig.Instance.GetChannelId == ChannelId.HuaWei  )
                {
                    StaticData.isLogining = false;
                    //直接做重登处理
                    StaticData.playerData.ClearSelectServerCache();
                    StaticData.UserName = "";
                    StaticData.PassWord = "";
                    ManagerController.Instance.BackToLogin();
					Debug.Log("PlatformSDKCallBack ChannelId ==  HuaWei");
					
                }
				else if(GameConfig.Instance.GetChannelId == ChannelId.YouLong)
				{
					
					  StaticData.isLogining = false;
                    //直接做重登处理
                    StaticData.playerData.ClearSelectServerCache();
                    StaticData.UserName = "";
                    StaticData.PassWord = "";
                    ManagerController.Instance.BackToLogin();
					Debug.Log("PlatformSDKCallBack ChannelId == YouLong");
					GameConfig.Instance.isSwitch = true;
				}
                else
                {
                    BoxManager.CreateOneDelMsgBox(LanguageTool.GetTextNoUpdate(1059), delegate()
                    {
                        StaticData.isLogining = false;
                        //直接做重登处理
                        StaticData.playerData.ClearSelectServerCache();
                        StaticData.UserName = "";
                        StaticData.PassWord = "";
                        ManagerController.Instance.BackToLogin();
						
                    });
                }
                
                break;
        }
    }
    string orderId;
    string payMentId;
    /// <summary>
    /// 支付回调
    /// </summary>
    /// <param name="data"></param>
    public void PayCallBackFun(string data)
    {
#if UNITY_IOS
        BoxManager.ClearNetMask();
#endif
        resultInfo = SuperSDKJson.JsonToResultInfo(data);

        switch (resultInfo.getPayAction())
        {

            case SuperSDKPayAction.PAY_SUCCESS://支付成功,需要CheckOrder,需要及时刷新首充状态
                if (resultInfo.hasResData())
                {
                    payInfo = new supersdkUnity.SuperSDKPayInfo(resultInfo.resData);
                }
                orderId = payInfo.getOrderId();
                payMentId = payInfo.getProductId();

                CheckOrder();
                //ChargePage chargePage = (ChargePage)PageManager.Instance.currentPage;
                //chargePage.GetComponent<ChargePage>().chargeData.GetComponent<ChargeData>().InitPayMent();
                //调用一下刷新
                break;
            case SuperSDKPayAction.PAY_FAIL://支付失败回调

                if (payInfo != null)
                {
                    errorInfo = new SuperSDKErrorInfo(payInfo);
                    int error_no = errorInfo.errorNo;
                    string error_msg = errorInfo.errorMsg;
                    Debug.Log("PayCallBackFun PAY_FAIL " + error_no + " msg " + error_msg);
                }
                else
                {
                    Debug.Log("PayCallBackFun PAY_FAIL PayInfo null");
                }

                break;
            case SuperSDKPayAction.PAY_CANCEL://支付取消回调
                Debug.Log("PayCallBackFun PAY_CANCEL");
                break;
            case SuperSDKPayAction.PAY_WAIT_CHECK://支付完成，等待确认
                if (resultInfo.hasResData())
                {
                    payInfo = new supersdkUnity.SuperSDKPayInfo(resultInfo.resData);
                }
                Debug.Log("[DEBUG] PAY_WAIT_CHECK");
                orderId = payInfo.getOrderId();
                payMentId = payInfo.getProductId();

                CheckOrder();
                break;
            default:
                Debug.Log("[DEBUG] DEFAULT");
                break;
        }


    }

    void CheckOrder() //订单查询
    {
        CSCheckOrder msg = new CSCheckOrder();

        msg.orderId = orderId;
        msg.paymentId = payMentId;
        NetAPI.SendHttp(OpDefine.CSCheckOrder, msg, ChekOrderCallBack);
    }

    long tick = 5000L;
    System.Timers.Timer timer;

    void ChekOrderCallBack(NetWork.Packets.Packet packet, bool bSuccess)
    {
        if (bSuccess)
        {
            SCCheckOrder msg = packet.kBody as SCCheckOrder;
            if (msg != null)
            {
                if (msg.transactionData.payStatus == "PAY_STATUS_SUCCESS")//充值成功,刷新人物状态
                {
                    //重新请求商品列表
                    ChargePage chargePage = (ChargePage)PageManager.Instance.currentPage;
                    chargePage.GetComponent<ChargePage>().chargeData.GetComponent<ChargeData>().InitPayMent();
                    //BoxManager.CreateMsgBox("充值成功", false);
                    //BoxManager.CreatePopupTextBox(TableTextBlo.GetText("chargeSuccess"));
#if UNITY_IOS
					PlatformSDK.GetInstance ().IOSPaySubmitData (payInfo.getOrderId(),payInfo.getOrderAmount());
#endif
                  

                }
                else//没充值成功,继续CheckOrder
                {
                    TickCheck();
                }
            }
        }

    }

    void TickCheck()
    {
        if (tick > 3600000L)//一个小时之后停止查询
        {

            timer.Enabled = false;
            return;
        }
        else
        {
            timer = new System.Timers.Timer(tick);
            Debug.Log("tick = " + tick);
            timer.Elapsed += new System.Timers.ElapsedEventHandler(Theout);
            timer.AutoReset = false;//是否只执行一次
            timer.Enabled = true;//是否执行Elapsed
            tick += tick;
        }
    }

    void Theout(object source, System.Timers.ElapsedEventArgs e)
    {

        CheckOrder();
    }

    void FailOrder(string paymentId, string orderId, ProtoBuf.Message.SuperSDKPayInfo info)
    {
        CSFailOrder msg = new CSFailOrder();
        msg.paymentId = paymentId;
        msg.orderId = orderId;
        msg.payInfo = info;
        NetAPI.SendHttp(OpDefine.CSFailOrder, msg, PCChargeCallBack);
    }
    void PCChargeCallBack(NetWork.Packets.Packet packet, bool bSuccess)
    {
        if (bSuccess)
        {
            SCFailOrder msg = packet.kBody as SCFailOrder;
            if (msg != null)
            {
                Debug.Log("orderFail PCChargeCallBack");
                //BoxManager.CreatePopupTextBox(TableTextBlo.GetText("chargeFailed"));
            }
        }
    }
#endif

    public void TestCharge() 
    {
        Debug.Log("TestCharge");
      
    }
}
